<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>弹幕展示</title>
    <link rel="stylesheet" th:href="@{/css/danmaku.css}">
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background-color: #060c21;
            color: #e1e1e1;
            margin: 0;
            padding: 0;
            display: flex;
            flex-direction: column;
            min-height: 100vh;
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
            background-image: url('https://api.vvhan.com/api/acgimg');
            overflow: hidden;
        }
        
        /* 设置背景图片样式 */
        body.has-custom-bg {
            background-image: none;
        }
        
        .bg-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: -1;
            background-color: rgba(0, 0, 0, 0.1);
        }
        
        .container {
            position: relative;
            width: 100%;
            height: 100vh;
            overflow: hidden;
        }
        
        /* 控制按钮样式 - 黑白透明 */
        .controls {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1000;
            display: flex;
            align-items: center;
            background: rgba(0, 0, 0, 0.1);
            padding: 10px 15px;
            border-radius: 30px;
            backdrop-filter: blur(5px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
        }
        
        button {
            background: rgba(0, 0, 0, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.3);
            color: #fff;
            padding: 8px 15px;
            border-radius: 25px;
            cursor: pointer;
            margin-right: 10px;
            transition: all 0.3s;
        }
        
        button:hover {
            background: rgba(255, 255, 255, 0.2);
            box-shadow: 0 0 10px rgba(255, 255, 255, 0.2);
        }
        
        .danmaku-item {
            position: absolute;
            display: flex;
            align-items: center;
            padding: 8px 16px;
            border-radius: 30px;
            background: rgba(0, 0, 0, 0.4);
            backdrop-filter: blur(3px);
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
            color: #fff;
            font-size: 15px;
            white-space: nowrap;
            transform: translateY(100px);
            opacity: 0;
            transition: all 0.5s ease-out;
            z-index: 10;
        }
        
        .danmaku-item.show {
            transform: translateY(0);
            opacity: 1;
        }
        
        .danmaku-item .avatar {
            width: 24px;
            height: 24px;
            border-radius: 50%;
            margin-right: 8px;
            object-fit: cover;
            border: 1px solid rgba(255, 255, 255, 0.3);
        }
        
        .danmaku-item .username {
            font-weight: bold;
            margin-right: 6px;
            color: #0cf2f8;
        }
        
        .type-1 { 
            background: rgba(10, 132, 255, 0.4);
            box-shadow: 0 0 15px rgba(10, 132, 255, 0.3); 
        }
        
        .type-2 { 
            background: rgba(0, 199, 190, 0.4);
            box-shadow: 0 0 15px rgba(0, 199, 190, 0.3); 
        }
        
        .type-3 { 
            background: rgba(94, 92, 230, 0.4);
            box-shadow: 0 0 15px rgba(94, 92, 230, 0.3); 
        }
        
        .type-4 { 
            background: rgba(255, 55, 95, 0.4);
            box-shadow: 0 0 15px rgba(255, 55, 95, 0.3); 
        }
        
        .type-5 { 
            background: rgba(255, 159, 10, 0.4);
            box-shadow: 0 0 15px rgba(255, 159, 10, 0.3); 
        }
        
        .status-message {
            margin-left: 15px;
            color: #ffffff;
            font-size: 14px;
            opacity: 0;
            transition: opacity 0.3s;
        }
        
        .status-message.visible {
            opacity: 1;
        }
        
        /* 返回按钮样式 - 黑白透明 */
        .back-link {
            position: fixed;
            bottom: 20px;
            left: 20px;
            color: #ffffff;
            text-decoration: none;
            display: flex;
            align-items: center;
            font-size: 14px;
            background: rgba(0, 0, 0, 0.1);
            padding: 8px 15px;
            border-radius: 25px;
            backdrop-filter: blur(5px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
            z-index: 1000;
        }
        
        .back-link:hover {
            background: rgba(255, 255, 255, 0.1);
        }
        
        .back-link svg path {
            fill: #ffffff;
        }
        
        .stats {
            position: fixed;
            bottom: 20px;
            right: 20px;
            background: rgba(0, 0, 0, 0.1);
            padding: 8px 15px;
            border-radius: 25px;
            backdrop-filter: blur(5px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
            color: rgba(255, 255, 255, 0.9);
            font-size: 12px;
            z-index: 1000;
        }
        
        /* 弹幕输入框样式 - 黑白透明 */
        .input-container {
            position: fixed;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            z-index: 1000;
            display: flex;
            align-items: center;
            background: rgba(0, 0, 0, 0.1);
            padding: 10px 15px;
            border-radius: 30px;
            backdrop-filter: blur(5px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
            transition: all 0.3s;
            max-width: 90%;
            width: 600px;
        }
        
        .input-container:hover {
            border-color: rgba(255, 255, 255, 0.4);
            box-shadow: 0 0 15px rgba(255, 255, 255, 0.1);
        }
        
        .input-container input {
            flex: 1;
            background: rgba(0, 0, 0, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            padding: 8px 15px;
            border-radius: 20px;
            color: #fff;
            margin-right: 10px;
            font-size: 15px;
        }
        
        .input-container input:focus {
            outline: none;
            box-shadow: 0 0 5px rgba(255, 255, 255, 0.3);
            border-color: rgba(255, 255, 255, 0.4);
        }
        
        .input-container select {
            background: rgba(0, 0, 0, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            padding: 8px;
            border-radius: 20px;
            color: #fff;
            margin-right: 10px;
            font-size: 14px;
        }
        
        .input-container button {
            background: rgba(0, 0, 0, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.3);
        }
        
        .input-container button:hover {
            background: rgba(255, 255, 255, 0.2);
        }
        
        .input-message {
            position: absolute;
            bottom: -25px;
            left: 50%;
            transform: translateX(-50%);
            color: #ffffff;
            font-size: 14px;
            background: rgba(0, 0, 0, 0.2);
            padding: 3px 10px;
            border-radius: 10px;
            backdrop-filter: blur(5px);
            border: 1px solid rgba(255, 255, 255, 0.1);
            opacity: 0;
            transition: opacity 0.3s;
        }
        
        .input-message.visible {
            opacity: 0.9;
        }
    </style>
</head>
<body th:class="${backgroundImage != null && backgroundImage != '' ? 'has-custom-bg' : ''}" th:style="${backgroundImage != null && backgroundImage != '' ? 'background-image: url(' + backgroundImage + ')' : ''}">
    <!-- 背景叠加层，用于调整透明度 -->
    <div class="bg-overlay" th:if="${backgroundImage != null && backgroundImage != ''}" th:style="'background-color: rgba(0, 0, 0, ' + ${backgroundOpacity ?: '0.5'} + ')'"></div>

    <div class="container" id="danmaku-container">
        <!-- 弹幕将在这里动态生成 -->
    </div>
    
    <div class="controls">
        <button id="refresh-btn">刷新弹幕</button>
        <button id="toggle-btn">暂停/继续</button>
        <span id="status-message" class="status-message">数据已更新!</span>
    </div>
    
    <a href="/" class="back-link">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" style="margin-right: 5px;">
            <path d="M10 20V14H14V20H19V12H22L12 3L2 12H5V20H10Z" fill="#ffffff"/>
        </svg>
        返回首页
    </a>
    
    <div class="stats" id="stats">
        载入中...
    </div>
    
    <div class="input-container" id="danmaku-input">
        <input type="text" id="content-input" placeholder="输入弹幕内容..." maxlength="50">
        <select id="color-select">
            <option value="1">蓝色</option>
            <option value="2">青色</option>
            <option value="3">紫色</option>
            <option value="4">红色</option>
            <option value="5">橙色</option>
        </select>
        <button id="send-btn">发送弹幕</button>
        <div class="input-message" id="input-message">弹幕发送成功!</div>
    </div>
    
    <script th:inline="javascript">
        document.addEventListener('DOMContentLoaded', function() {
            const refreshBtn = document.getElementById('refresh-btn');
            const toggleBtn = document.getElementById('toggle-btn');
            const statusMessage = document.getElementById('status-message');
            const danmakuContainer = document.getElementById('danmaku-container');
            const statsDisplay = document.getElementById('stats');
            
            // 初始弹幕数据
            let danmakus = /*[[${danmakus}]]*/ [];
            let isPaused = false;
            let displayQueue = [];
            let displayInterval = null;
            let currentDisplayIndex = 0;
            
            // 轨道管理
            const trackHeight = 40; // 每个轨道的高度
            let tracks = []; // 已占用的轨道
            
            // 初始化轨道
            function initTracks() {
                const viewportHeight = window.innerHeight;
                const maxTracks = Math.floor(viewportHeight / trackHeight);
                tracks = Array(maxTracks).fill(false); // false 表示轨道空闲
                console.log(`初始化 ${maxTracks} 条轨道`);
            }
            
            // 寻找可用轨道
            function findAvailableTrack() {
                // 首先尝试找一个空轨道
                for (let i = 0; i < tracks.length; i++) {
                    if (!tracks[i]) {
                        return i;
                    }
                }
                
                // 如果所有轨道都被占用，随机选择一个
                return Math.floor(Math.random() * tracks.length);
            }
            
            // 标记轨道使用状态
            function markTrack(trackIndex, isOccupied) {
                if (trackIndex >= 0 && trackIndex < tracks.length) {
                    tracks[trackIndex] = isOccupied;
                }
            }
            
            // 获取用户头像URL
            function getUserAvatar(danmaku) {
                console.log("处理用户头像，用户数据:", danmaku.user);
                if (danmaku.user && danmaku.user.profileImage) {
                    console.log("使用用户头像:", danmaku.user.profileImage);
                    // 检查头像URL是否有效
                    return danmaku.user.profileImage;
                } else if (danmaku.user && danmaku.user.username) {
                    console.log("生成默认头像:", danmaku.user.username);
                    // 如果没有头像，使用基于用户名的默认头像
                    return `https://api.dicebear.com/6.x/bottts/svg?seed=${encodeURIComponent(danmaku.user.username)}`;
                }
                console.log("生成随机头像");
                // 如果没有用户或用户名，使用随机头像
                return `https://api.dicebear.com/6.x/bottts/svg?seed=random${Math.random().toString(36).substring(2, 8)}`;
            }
            
            // 计算动画持续时间
            function calculateDuration() {
                // 根据屏幕宽度计算合适的动画时间
                const viewportWidth = window.innerWidth;
                // 速度系数：屏幕越宽，动画时间越长
                return viewportWidth * 0.01 + Math.random() * 2 + 8; // 8-12秒基本时间，加上随机变化
            }
            
            // 显示单条弹幕
            function displayDanmaku(danmaku) {
                if (isPaused) return;
                
                // 寻找可用轨道
                const trackIndex = findAvailableTrack();
                markTrack(trackIndex, true); // 标记轨道为已占用
                
                // 创建弹幕元素
                const element = document.createElement('div');
                element.className = `danmaku-item type-${danmaku.colorType || 1}`;
                
                // 获取用户名
                const username = danmaku.user && danmaku.user.username ? danmaku.user.username : '匿名';
                
                // 获取用户头像
                const avatarUrl = getUserAvatar(danmaku);
                
                // 设置弹幕内容
                element.innerHTML = `
                    <img class="avatar" src="${avatarUrl}" alt="${username}" onerror="this.src='https://api.dicebear.com/6.x/bottts/svg?seed=default'" />
                    <span class="username">${username}</span>${danmaku.content}
                `;
                
                // 计算动画持续时间
                const duration = calculateDuration();
                
                // 设置弹幕在轨道上的垂直位置
                element.style.top = `${trackIndex * trackHeight}px`;
                element.style.right = '-300px'; // 确保从屏幕右侧外开始
                
                // 添加到容器
                danmakuContainer.appendChild(element);
                
                // 触发显示
                setTimeout(() => {
                    element.classList.add('show');
                    
                    // 设置动画
                    element.style.transition = `transform ${duration}s linear, opacity 0.5s ease`;
                    element.style.transform = 'translateX(-2000px)'; // 向左移动足够的距离
                }, 50);
                
                // 动画结束后移除元素
                setTimeout(() => {
                    if (element.parentNode) {
                        element.classList.remove('show');
                        setTimeout(() => {
                            if (element.parentNode) {
                                element.parentNode.removeChild(element);
                                markTrack(trackIndex, false); // 释放轨道
                            }
                        }, 500);
                    } else {
                        markTrack(trackIndex, false); // 确保轨道被释放
                    }
                }, duration * 1000 + 500);
            }
            
            // 处理弹幕队列展示
            function processDanmakuQueue() {
                if (isPaused || displayQueue.length === 0) return;
                
                // 每次显示1条，从队列中取出
                if (currentDisplayIndex >= displayQueue.length) {
                    currentDisplayIndex = 0;
                }
                
                const danmaku = displayQueue[currentDisplayIndex];
                displayDanmaku(danmaku);
                
                // 移到下一条
                currentDisplayIndex++;
                
                // 更新统计信息
                updateStats();
            }
            
            // 更新统计信息
            function updateStats() {
                const activeCount = document.querySelectorAll('.danmaku-item').length;
                statsDisplay.textContent = `共 ${danmakus.length} 条弹幕 | 当前显示: ${activeCount}`;
            }
            
            // 获取最新弹幕数据
            function fetchDanmakus() {
                fetch('/danmaku/api/data')
                    .then(response => response.json())
                    .then(data => {
                        console.log("获取到弹幕数据:", data);
                        // 显示刷新状态
                        statusMessage.classList.add('visible');
                        setTimeout(() => {
                            statusMessage.classList.remove('visible');
                        }, 3000);
                        
                        danmakus = data;
                        displayQueue = [...danmakus];
                        
                        // 打乱顺序
                        displayQueue.sort(() => Math.random() - 0.5);
                        
                        // 更新统计信息
                        updateStats();
                    })
                    .catch(error => {
                        console.error('获取弹幕数据失败:', error);
                    });
            }
            
            // 初始化弹幕队列
            function initializeDisplay() {
                // 初始化轨道
                initTracks();
                
                if (danmakus && danmakus.length > 0) {
                    displayQueue = [...danmakus];
                    
                    // 随机排序弹幕
                    displayQueue.sort(() => Math.random() - 0.5);
                    
                    // 设置定时显示
                    if (displayInterval) {
                        clearInterval(displayInterval);
                    }
                    
                    displayInterval = setInterval(processDanmakuQueue, 1000); // 每秒发射一条弹幕
                    
                    // 更新统计信息
                    updateStats();
                } else {
                    // 如果没有弹幕数据，尝试获取
                    fetchDanmakus();
                }
            }
            
            // 监听窗口大小变化，重新计算轨道
            window.addEventListener('resize', function() {
                initTracks();
            });
            
            // 绑定刷新按钮事件
            if (refreshBtn) {
                refreshBtn.addEventListener('click', fetchDanmakus);
            }
            
            // 绑定暂停/继续按钮事件
            if (toggleBtn) {
                toggleBtn.addEventListener('click', function() {
                    isPaused = !isPaused;
                    this.textContent = isPaused ? '继续' : '暂停';
                    
                    if (!isPaused && !displayInterval) {
                        displayInterval = setInterval(processDanmakuQueue, 1000);
                    }
                });
            }
            
            // 弹幕输入相关
            const contentInput = document.getElementById('content-input');
            const colorSelect = document.getElementById('color-select');
            const sendBtn = document.getElementById('send-btn');
            const inputMessage = document.getElementById('input-message');
            
            // 发送弹幕
            function sendDanmaku() {
                const content = contentInput.value.trim();
                if (!content) {
                    showInputMessage('请输入弹幕内容!', false);
                    return;
                }
                
                const colorType = colorSelect.value;
                
                fetch('/danmaku/api/send', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `content=${encodeURIComponent(content)}&colorType=${colorType}`
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络错误');
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('弹幕发送成功:', data);
                    
                    // 清空输入框
                    contentInput.value = '';
                    
                    // 显示成功消息
                    showInputMessage('弹幕发送成功!', true);
                    
                    // 刷新弹幕数据
                    setTimeout(fetchDanmakus, 500);
                    
                    // 立即显示新发送的弹幕
                    if (data) {
                        // 构造与API一致的弹幕对象
                        const newDanmaku = {
                            id: data.id || Date.now(),
                            content: content,
                            colorType: parseInt(colorType),
                            createdTime: new Date().toISOString(),
                            user: /*[[${#authentication.principal != 'anonymousUser' ? #authentication.principal : null}]]*/ null
                        };
                        
                        // 立即显示这条弹幕
                        displayDanmaku(newDanmaku);
                    }
                })
                .catch(error => {
                    console.error('发送弹幕失败:', error);
                    showInputMessage('发送失败: ' + error.message, false);
                });
            }
            
            // 显示输入框消息
            function showInputMessage(message, isSuccess) {
                inputMessage.textContent = message;
                inputMessage.style.backgroundColor = isSuccess ? 'rgba(255, 255, 255, 0.2)' : 'rgba(0, 0, 0, 0.3)';
                inputMessage.style.borderColor = isSuccess ? 'rgba(255, 255, 255, 0.3)' : 'rgba(255, 255, 255, 0.2)';
                inputMessage.classList.add('visible');
                
                setTimeout(() => {
                    inputMessage.classList.remove('visible');
                }, 3000);
            }
            
            // 绑定发送按钮事件
            if (sendBtn) {
                sendBtn.addEventListener('click', sendDanmaku);
            }
            
            // 绑定输入框回车事件
            if (contentInput) {
                contentInput.addEventListener('keypress', function(e) {
                    if (e.key === 'Enter') {
                        sendDanmaku();
                    }
                });
            }
            
            // 初始化
            initializeDisplay();
            
            // 定时获取最新弹幕
            setInterval(fetchDanmakus, 30000);
        });
    </script>
</body>
</html> 